import axios from "axios";
import router from "@/router";

const request = axios.create({
    baseURL: 'http://localhost:9090', // 后端的接口地址
    timeout: 5000, // 请求超时时间
});

request.interceptors.request.use(
    config => {
        config.headers['Content-Type'] = 'application/json;charset=utf-8';
        let user=JSON.parse(localStorage.getItem('honey-user') || '{}')
        config.headers['token']=user.token //设置请求头
        return config;
    },
    error => {
        console.error('request error:', error);
        return Promise.reject(error);
    }
);
request.interceptors.response.use(
    response => {
        if (response.status !== 200) {
            console.error('Unexpected status code:', response.status);
            return Promise.reject(new Error(`Request failed with status ${response.status}`));
        }
        const data = response.data;
        if (!data) {
            console.warn('Empty response received');
            return Promise.reject(new Error('Empty response'));
        }
        if(data.code=='401'){
            router.push('/login')
        }
        return data; // 假设后端总是返回JSON对象或数组，无需额外处理
    },
    error => {
        console.error('response error:', error);
        return Promise.reject(error);
    }
);

export default request;